package cn.data.collection.interceptor;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

import org.jsoup.nodes.Document;

import cn.data.collection.constant.CollectionParaConstant;
import cn.data.collection.constant.InitPropertiesConstant;
import cn.data.collection.constant.ThreadCommonData;
import cn.data.collection.util.DBConnection;
import cn.data.collection.util.DateUtils;
import cn.data.collection.util.HttpClientUtils;
import cn.data.collection.util.LoggerUtils;
import cn.data.collection.util.PropertiesUtils;
import cn.data.collection.util.UnicodeCharUtil;
import cn.smy.dama2.CrackValidateCode;

public class AutoLimitCollectionThread implements Runnable {
	private int currenThreadNum;
	private HttpClientUtils httpClientUtils = new HttpClientUtils();

	public AutoLimitCollectionThread(int currenThreadNum) {
		super();
		this.currenThreadNum = currenThreadNum;
	}

	@Override
	public void run() {
		try {
			httpClientUtils.initHttpClient();
			ThreadCommonData.LST_HTTPCLIENTUTILS.add(httpClientUtils);
			Long collectStartNum = Long.valueOf(PropertiesUtils.getInstance().getINITDATA().get(InitPropertiesConstant.COLLECTION_START_NUM).toString());
			Long collectionAmount = Long.valueOf(PropertiesUtils.getInstance().getINITDATA().get(InitPropertiesConstant.COLLECTION_AMOUNT).toString());
			Long collectionThreadNum = Long.valueOf(PropertiesUtils.getInstance().getINITDATA().get(InitPropertiesConstant.COLLECTION_THREAD_NUM).toString());
			Long collectTimeOut = Long.valueOf(PropertiesUtils.getInstance().getINITDATA().get(InitPropertiesConstant.COLLECTION_TIME_OUT).toString());
			Long threadBetweenNum = (collectionAmount/collectionThreadNum);//区间值
			Long startNum = collectStartNum+(threadBetweenNum*currenThreadNum)+1;
			Long endNum = collectStartNum+threadBetweenNum;
			
			try{
				for(long i = startNum;i<endNum;i++){
					String currentZhucehao = String.valueOf(i);
					if(ThreadCommonData.HAVED_COLLECTION_COMPANY.get(currentZhucehao)!=null){
						continue;
					}
					String strRadom = String.valueOf(Math.random());
					try{
						StringBuffer strImgUrl = new StringBuffer();
						strImgUrl.append(CollectionParaConstant.VALIDATE_IMG_URL);
						strImgUrl.append(strRadom);
						
						long startGetMainPagTime = System.currentTimeMillis();
						httpClientUtils.loadUrl(CollectionParaConstant.MAIN_URL);
						long endGetMainPagTime = System.currentTimeMillis();
						LoggerUtils.getInstance().error("注册号:"+currentZhucehao+"初始化首页耗费时间:"+(endGetMainPagTime-startGetMainPagTime)+"毫秒！");
						httpClientUtils.downloadImg(strImgUrl.toString(), strRadom);
						long downloadImgTime = System.currentTimeMillis();
						LoggerUtils.getInstance().error("注册号:"+currentZhucehao+"下载图片耗费时间:"+(downloadImgTime-endGetMainPagTime)+"毫秒！");
						
						String validateCode = CrackValidateCode.getInstance().getValidateCode(strRadom);
						long damaTime = System.currentTimeMillis();
						LoggerUtils.getInstance().error("注册号:"+currentZhucehao+"验证码:"+validateCode+"打码耗费时间:"+(damaTime-downloadImgTime)+"毫秒！");
						
						Map<String, String> checkCodeParamMap = new HashMap<String, String>();
						checkCodeParamMap.put(CollectionParaConstant.PARAM_TEXTFIELD,currentZhucehao);
						checkCodeParamMap.put(CollectionParaConstant.PARAM_CODE,validateCode);
						String strCheckCode = httpClientUtils.postForm(CollectionParaConstant.CHECKCODEURL, checkCodeParamMap).toString();
						LoggerUtils.getInstance().error("注册号:"+currentZhucehao+"获取到的验证码:"+strCheckCode);
						LoggerUtils.getInstance().error("注册号:"+currentZhucehao+"修正的验证码:"+UnicodeCharUtil.getFixStr(strCheckCode.substring("{\"flag\":\"1\",\"textfield\":\"".length(), strCheckCode.length()-2)));
						
						Map<String, String> getInfoParamMap = new HashMap<String, String>();
						getInfoParamMap.put(CollectionParaConstant.PARAM_TEXTFIELD,UnicodeCharUtil.getFixStr(strCheckCode.substring("{\"flag\":\"1\",\"textfield\":\"".length(), strCheckCode.length()-2)));
						getInfoParamMap.put(CollectionParaConstant.PARAM_CODE,validateCode);
						String strInfo = httpClientUtils.postForm(CollectionParaConstant.GETINFOURL, getInfoParamMap);
						LoggerUtils.getInstance().error("注册号:"+currentZhucehao+"获取到的企业为:"+strInfo);
						
						Document doc = httpClientUtils.instr2Jsoup(strInfo);
						String company = doc.select(".list a").html();
						this.data2DB(currentZhucehao,company);
						ThreadCommonData.HAVED_COLLECTION_COMPANY.put(currentZhucehao, company);
						Thread.sleep(collectTimeOut);
					} catch (Exception e) {
						LoggerUtils.getInstance().error("注册号:"+currentZhucehao+"异常采集错误!",e);
					}
				}
			} catch (Exception e) {
				LoggerUtils.getInstance().error("线程"+currenThreadNum+"错误，异常停止!",e);
			}
		} catch (Exception e) {
			LoggerUtils.getInstance().error(e);
		} finally {
			httpClientUtils.releaseConnection();
		}
	}

	private void data2DB(String shoulihao, String companyName) throws SQLException {
		Statement st = null;
		Connection conn = null;
		String sql = "insert into company (shoulihao,companyName,createDateTime,dbCurrentDateTime) values ('"
				+ shoulihao + "','" + companyName + "','" + DateUtils.nowDate(DateUtils.DATETIME_FORMATE) + "',now())";
		try {
			conn = DBConnection.getConnection();
			st = conn.createStatement();
			st.executeUpdate(sql);
		} catch (SQLException e) {
			throw e;
		} finally {
			DBConnection.releaseConnection(conn, st, null);
		}
	}

}
